<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '../utils/request'

const router = useRouter()

// 作者列表数据
const authors = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 控制添加作者弹窗的显示
const dialogVisible = ref(false)
const newAuthorName = ref('')

// 控制编辑作者对话框的显示
const editDialogVisible = ref(false)
const editingAuthor = ref(null)

// 获取作者列表
const getAuthorList = async () => {
  try {
    const response = await request.get('/api/authors', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      authors.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取作者列表失败:', error)
  }
}

// 添加作者
const addAuthor = async () => {
  if (!newAuthorName.value.trim()) {
    ElMessage.warning('请输入作者名称')
    return
  }
  
  try {
    const response = await request.post('/api/authors', {
      name: newAuthorName.value.trim()
    })
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogVisible.value = false
      newAuthorName.value = ''
      getAuthorList()
    }
  } catch (error) {
    console.error('添加作者失败:', error)
    ElMessage.error('添加失败')
  }
}

// 打开编辑对话框
const openEditDialog = (author) => {
  editingAuthor.value = { ...author }
  editDialogVisible.value = true
}

// 更新作者
const updateAuthor = async () => {
  try {
    const response = await request.put(`/api/authors/${editingAuthor.value.id}`, {
      name: editingAuthor.value.name
    })
    if (response.data.code === 200) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      editingAuthor.value = null
      getAuthorList()
    }
  } catch (error) {
    console.error('更新作者失败:', error)
    ElMessage.error('更新失败')
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAuthorList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getAuthorList()
}

// 组件挂载时获取作者列表
onMounted(() => {
  getAuthorList()
})

// 控制删除确认对话框的显示
const deleteDialogVisible = ref(false)
const authorToDelete = ref(null)

// 删除作者
const deleteAuthor = async () => {
  try {
    const response = await request.delete(`/api/authors/${authorToDelete.value.id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      authorToDelete.value = null
      getAuthorList()
    }
  } catch (error) {
    console.error('删除作者失败:', error)
    ElMessage.error('删除失败')
  }
}

// 确认删除作者
const confirmDelete = (author) => {
  authorToDelete.value = author
  deleteDialogVisible.value = true
}
</script>

<template>
  <div class="author-manager">
    <div class="header">
      <div class="header-left">
        <el-button type="text" @click="router.push('/')">
          <el-icon><arrow-left /></el-icon>
        </el-button>
        <h2>作者管理</h2>
      </div>
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon><el-icon-plus /></el-icon>
        添加作者
      </el-button>
    </div>

    <el-table :data="authors" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="作者名称" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="confirmDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加作者弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加作者"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="作者名称">
          <el-input v-model="newAuthorName" placeholder="请输入作者名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addAuthor">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑作者对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑作者"
      width="30%"
    >
      <el-form>
        <el-form-item label="作者名称">
          <el-input v-model="editingAuthor.name" placeholder="请输入作者名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateAuthor">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="30%"
      :close-on-click-modal="false"
    >
      <span>确定要删除作者 "{{ authorToDelete?.name }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteAuthor">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.author-manager {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>